package es.battleship.resource;

import java.util.List;
import java.util.logging.Logger;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

import es.battleship.api.service.GameNotificationService;
import es.battleship.api.service.GameService;
import es.battleship.model.PlayerPair;


@Controller
@Path("/battleship")
public class GameResource {
	Logger  logger = Logger.getLogger(GameResource.class.getName());
	
	private GameNotificationService notification;
	private GameService gameService;

	@Autowired
	public void setNotification(GameNotificationService notification) {
		this.notification = notification;
	}

	@Autowired
	public void setGameService(GameService gameService) {
		this.gameService = gameService;
	}

	@GET
    @Path("invite/{name}")
	@Produces("application/json")
    public String invite(@Context SecurityContext sc, @PathParam("name") String name) throws Exception {
		logger.info("invite " + sc.getUserPrincipal().getName() +  " to " + name);
		
		String invitationId = gameService.invite(sc.getUserPrincipal().getName() ,name);
		
		notification.invite(sc.getUserPrincipal().getName(), name);
		
		return invitationId;
    }
	
	@GET
    @Path("accept/{id}")
	@Produces("application/json")
    public void accept(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception {
		logger.info("accept " + id);
		
		String player = gameService.accept(id,sc.getUserPrincipal().getName());
		
		notification.accept(player, Long.toString(id));
		
		

    }
	
	@GET
	@Path("list")
	@Produces("application/json")
	public List<PlayerPair> getGames(@Context SecurityContext sc) {
		logger.info("getGames " + sc.getUserPrincipal().getName());
		
		return gameService.getAllFromUser(sc.getUserPrincipal().getName());
	}
	
	
	@GET
    @Path("chat/{name}")
	@Produces("application/json")
    public void chat(@Context SecurityContext sc, @PathParam("name") String name) {
		logger.info(sc.getUserPrincipal().getName()+ " invite to  " + name);
		
		JID jid = new JID(name);
		
	    XMPPService xmpp = XMPPServiceFactory.getXMPPService();
	    xmpp.sendInvitation(jid);
    }

}
